package com.papper.mng.controller.sys;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.papper.common.bean.sys.SysSystem;
import com.papper.common.enums.DataStatusEnum;
import com.papper.common.exception.ServiceException;
import com.papper.common.service.sys.SysModelService;
import com.papper.common.service.sys.SysResourceService;
import com.papper.common.service.sys.SysSystemService;
import com.papper.mng.controller.BaseAction;
import com.papper.mng.domain.DwzResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author:Lajiao
 * @Date:2014年7月14日
 * @Time:下午3:49:44
 * @Description:部署系统
 */
@Controller
@RequestMapping("/sys/system")
public class SysSystemAction extends BaseAction {
    @Autowired
    SysSystemService   sysSystemService;
    @Autowired
    SysModelService    sysModelService;
    @Autowired
    SysResourceService sysResourceService;

    /**
     * 部署系统首页
     *
     * @return
     */
    @GetMapping(value = "")
    public String execute(HttpServletRequest _request, Model model) {
        List<SysSystem> systemList = sysSystemService.findAll();
        model.addAttribute("systemList", systemList);
        return render("sys/system/index");
    }

    /**
     * 部署系统_新增
     *
     * @param _response
     * @throws IOException
     */
    @GetMapping(value = "/add")
    public String add_get(HttpServletResponse _response, Model model) {
        return render("sys/system/add");
    }

    @PostMapping(value = "/add")
    @ResponseBody
    public DwzResponse add_post(HttpServletRequest _request, HttpServletResponse _response, SysSystem sysSystem) {
        try {
            checkSuperCert(_request);
        } catch (ServiceException e) {
            return new DwzResponse("300", e.getMessage());
        }
        if (sysSystem == null) {
            return new DwzResponse("300", "参数异常！");
        }

        Map<String, String> systemConfig = Maps.newHashMap();
        // 系统配置信息
        systemConfig.put("systemLogo", _request.getParameter("systemLogo"));
        systemConfig.put("systemBackground", _request.getParameter("systemBackground"));
        systemConfig.put("systemIcp", _request.getParameter("systemIcp"));
        systemConfig.put("systemCustomePhone", _request.getParameter("systemCustomePhone"));
        //系统缓存配置
        systemConfig.put("systemCacheLocal", _request.getParameter("systemCacheLocal"));
        systemConfig.put("systemCacheRemote", _request.getParameter("systemCacheRemote"));
        //系统文件配置
        systemConfig.put("systemFileExcelPath", _request.getParameter("systemFileExcelPath"));
        systemConfig.put("systemFileKeyPath", _request.getParameter("systemFileKeyPath"));
        systemConfig.put("systemFilePicPath", _request.getParameter("systemFilePicPath"));
        systemConfig.put("systemFilePicHttp", _request.getParameter("systemFilePicHttp"));
        //系统模版
        systemConfig.put("systemTemplate", _request.getParameter("systemTemplate"));
        sysSystem.setSystemDesc(JSON.toJSONString(systemConfig));

        sysSystem.setDataStatus(DataStatusEnum.OPEN.getCode());
        sysSystem.setCreateTime(new Date());
        sysSystem.setModifyTime(new Date());
        try {
            sysSystemService.save(sysSystem);
            return new DwzResponse("200", "部署系统新增成功!!!");
        } catch (Exception e) {
            e.printStackTrace();
            return new DwzResponse("300", "系统错误,请稍候再试!!![" + e.getMessage() + "]");
        }
    }

    /**
     * 部署系统_更新
     *
     * @param _response
     * @throws IOException
     */
    @GetMapping(value = "/edit")
    public String edit_get(HttpServletResponse _response, Model model, Long id) throws IOException {
        SysSystem sysSystem = sysSystemService.findById(id);
        model.addAttribute("entity", sysSystem);
        JSONObject systemDesc = JSON.parseObject(sysSystem.getSystemDesc());
        model.addAttribute("systemDesc", systemDesc);
        return render("sys/system/edit");
    }

    @PostMapping(value = "/edit")
    @ResponseBody
    public DwzResponse edit_post(HttpServletRequest _request, HttpServletResponse _response, SysSystem sysSystem) throws IOException {
        try {
            checkSuperCert(_request);
        } catch (ServiceException e) {
            return new DwzResponse("300", e.getMessage());
        }
        if (sysSystem == null || sysSystem.getId() == null) {
            return new DwzResponse("300", "参数异常！");
        }
        Map<String, String> systemConfig = Maps.newHashMap();
        // 系统配置信息
        systemConfig.put("systemLogo", _request.getParameter("systemLogo"));
        systemConfig.put("systemBackground", _request.getParameter("systemBackground"));
        systemConfig.put("systemIcp", _request.getParameter("systemIcp"));
        systemConfig.put("systemCustomePhone", _request.getParameter("systemCustomePhone"));
        //系统缓存配置
        systemConfig.put("systemCacheLocal", _request.getParameter("systemCacheLocal"));
        systemConfig.put("systemCacheRemote", _request.getParameter("systemCacheRemote"));
        //系统文件配置
        systemConfig.put("systemFileExcelPath", _request.getParameter("systemFileExcelPath"));
        systemConfig.put("systemFileKeyPath", _request.getParameter("systemFileKeyPath"));
        systemConfig.put("systemFilePicPath", _request.getParameter("systemFilePicPath"));
        systemConfig.put("systemFilePicHttp", _request.getParameter("systemFilePicHttp"));
        //系统模版
        systemConfig.put("systemTemplate", _request.getParameter("systemTemplate"));
        sysSystem.setSystemDesc(JSON.toJSONString(systemConfig));
        sysSystem.setModifyTime(new Date());
        try {
            sysSystemService.update(sysSystem);
            return new DwzResponse("200", "部署系统修改成功!!!");
        } catch (Exception e) {
            e.printStackTrace();
            return new DwzResponse("300", "系统错误,请稍候再试!!![" + e.getMessage() + "]");
        }
    }

    /**
     * 部署系统_更新
     *
     * @param _response
     * @throws IOException
     */
    @GetMapping(value = "/editAll")
    public String edit_get(HttpServletResponse _response, Model model) throws IOException {
        return render("sys/system/editAll");
    }

    @PostMapping(value = "/editAll")
    @ResponseBody
    public DwzResponse editAll_post(HttpServletRequest _request, HttpServletResponse _response) throws IOException {
        try {
            checkSuperCert(_request);
        } catch (ServiceException e) {
            return new DwzResponse("300", e.getMessage());
        }
        List<String> updField = Lists.newArrayList();
        updField.add("systemLogo");
        updField.add("systemBackground");
        updField.add("systemIcp");
        updField.add("systemCustomePhone");
        updField.add("systemCacheLocal");
        updField.add("systemCacheRemote");
        updField.add("systemFileExcelPath");
        updField.add("systemFileKeyPath");
        updField.add("systemFilePicPath");
        updField.add("systemFilePicHttp");
        List<SysSystem> sysSystemList = sysSystemService.findAll();
        if (sysSystemList != null) {
            for (SysSystem sysSystem : sysSystemList) {
                JSONObject systemConfig = JSON.parseObject(sysSystem.getSystemDesc());
                for (String key : updField) {
                    if (!StringUtil.isEmpty(_request.getParameter(key))) {
                        systemConfig.put(key, _request.getParameter(key));
                    }
                }
                sysSystem.setSystemDesc(systemConfig.toJSONString());
                sysSystem.setModifyTime(new Date());
                try {
                    sysSystemService.update(sysSystem);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return new DwzResponse("200", "部署系统一健修改成功!!!");
    }

    /**
     * 部署系统_删除
     *
     * @param _response
     * @param id
     * @throws IOException
     */
    @PostMapping(value = "/del")
    @ResponseBody
    public DwzResponse del(HttpServletRequest _request, HttpServletResponse _response, Long id) throws IOException {
        try {
            checkSuperCert(_request);
        } catch (ServiceException e) {
            return new DwzResponse("300", e.getMessage());
        }
        if (id == null || id.intValue() <= 0) {
            return new DwzResponse("300", "参数异常！");
        }
        try {
            // 删除系统
            sysSystemService.deleteById(id);
            // 删除模块
            sysModelService.deleteBySystemId(id);
            // 删除模块资源
            sysResourceService.deleteBySystemId(id);
            // 删除系统所属角色
            // 删除系统角色账户
            return new DwzResponse("200", "系统删除成功!!!");
        } catch (Exception e) {
            e.printStackTrace();
            return new DwzResponse("300", "系统错误,请稍候再试!!![" + e.getMessage() + "]");
        }
    }

    /**
     * 部署系统_全系统替换
     */
    @GetMapping(value = "/replaceAll")
    public String replaceAll_get() {
        return render("sys/system/replaceAll");
    }

    @PostMapping(value = "/replaceAll")
    @ResponseBody
    public DwzResponse replaceAll_post(HttpServletRequest _request, HttpServletResponse _response, String oldName, String newName, String oldIp, String newIp) {
        try {
            checkSuperCert(_request);
        } catch (ServiceException e) {
            return new DwzResponse("300", e.getMessage());
        }
        List<String> updField = Lists.newArrayList();
        updField.add("systemLogo");
        updField.add("systemBackground");
        updField.add("systemIcp");
        updField.add("systemCustomePhone");
        updField.add("systemCdnPath");
        updField.add("systemCacheLocal");
        updField.add("systemCacheRemote");
        updField.add("systemFileExcelPath");
        updField.add("systemFileKeyPath");
        updField.add("systemFilePicPath");
        updField.add("systemFilePicHttp");

        List<SysSystem> sysSystemList = sysSystemService.findAll();
        if (sysSystemList != null) {
            for (SysSystem sysSystem : sysSystemList) {
                sysSystem.setSystemName(sysSystem.getSystemName().replace(oldName, newName));
                sysSystem.setSystemHost(sysSystem.getSystemHost().replace(oldIp, newIp));
                sysSystem.setSystemUrl(sysSystem.getSystemUrl().replace(oldIp, newIp));

                JSONObject systemConfig = JSON.parseObject(sysSystem.getSystemDesc());
                for (String key : updField) {
                    if (!StringUtil.isEmpty(_request.getParameter(key))) {
                        systemConfig.put(key, systemConfig.getString(key).replace(oldIp, newIp));
                    }
                }
                sysSystem.setSystemDesc(systemConfig.toJSONString());
                sysSystem.setModifyTime(new Date());
                try {
                    sysSystemService.update(sysSystem);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return new DwzResponse("200", "部署系统一健变更成功!!!");
    }

    /**
     * 部署系统_详情
     *
     * @return
     */
    @GetMapping(value = "/detail")
    public String detail(Model model, Long id) {
        SysSystem sysSystem = sysSystemService.findById(id);
        model.addAttribute("entity", sysSystem);
        return render("sys/system/detail");
    }
}